import styled from '@/pages/login/index.module.scss'
import {useCallback, useEffect, useMemo, useState} from 'react'
import {Form, Input, ColProps, Button, message} from 'antd'
import {LoginFormsType, LoginFormType, RegisterFormItemType, RegisterFormType} from '@/type/user'
import rules from '@/utils/rules'
import {login, register} from '@/api'
import {generateRandomPhoneNumber} from '@/utils'
import {useNavigate} from 'react-router-dom'


const header = [
	'登录',
	'注册'
]
const loginFormLabelCol:ColProps = {
	span: 5
}

const btnStyle = {
	display: 'flex',
	alignItems: 'center',
	justifyContent: 'center',
	width: '100%',
	margin: '0 auto'
}

const {Item, useForm} = Form

const LoginForm:LoginFormsType[] = [
	{
		label: '用户名',
		name: ['username'],
		rules: [
			{
				required: true,
				message: '请输入用户名'
			},
			{
				pattern: rules.subscriber('chineseName'),
				message: '请输入2到16位汉字'
			}
		]
	},
	{
		label: '密码',
		name: ['password'],
		rules: [
			{
				required: true,
				message: '请输入密码'
			},
		]
	}
]

const FormLogin = () => {
	const navigate = useNavigate()

	const [form] = useForm()

	const onFinish = useCallback((values:LoginFormType) => {
		login(values).then(res => {
			if (res.code === 200) {
				message.success(res.message)
				sessionStorage.setItem("token", res.data.token)
				sessionStorage.setItem("info", JSON.stringify(res.data.user))
				navigate("/home/main", {
					replace: true
				})
			}
		})
	}, [])

	return (
		<Form
			form={form}
			colon={true}
			layout={'horizontal'}
			labelCol={loginFormLabelCol}
			onFinish={onFinish}
		>
			{
				LoginForm.map((item,index) => (
					<Item<LoginFormType> {...item} key={index}>
						<Input></Input>
					</Item>
				))
			}
			<Item>
				<div style={btnStyle}>
					<Button block type={'primary'} htmlType={'submit'}>登录</Button>
				</div>
			</Item>
		</Form>
	)
}

const registerPhoneForm:LoginFormsType<RegisterFormItemType>[] = [
	{
		label: '电话',
		name: ['phone'],
		rules: [
			{
				required: true,
				message: '请输入手机号'
			},
			{
				pattern: rules.subscriber('phone'),
				message: '请输入正确的手机号'
			}
		]
	}
]

const registerForm: LoginFormsType<RegisterFormItemType>[] = [].concat(LoginForm, registerPhoneForm)

const FormRegister = () => {
	const [form] = useForm()

	const [formValue, setFormValue] = useState<RegisterFormType>({
		username: "",
		password: "",
		phone: ""
	})

	const onFinish = useCallback((values: RegisterFormType) => {
		register(values).then(res => {
			if (res.code === 200) {
				message.success(res.message)
			}
		})
	}, [])

	useEffect(() => {
		setFormValue((x) => ({
			...x,
			phone: generateRandomPhoneNumber()
		}))
		form.setFieldValue(["phone"], generateRandomPhoneNumber())
	}, [])

	return (
		<Form
			form={form}
			colon={true}
			layout={'horizontal'}
			labelCol={loginFormLabelCol}
			initialValues={formValue}
			onFinish={onFinish}
		>
			{
				registerForm.map((item,index) => (
					<Item<RegisterFormType> {...item} key={index}>
						<Input></Input>
					</Item>
				))
			}
			<Item>
				<div style={btnStyle}>
					<Button block type={'primary'} htmlType={'submit'}>注册</Button>
				</div>
			</Item>
		</Form>
	)
}

const Login = () => {

	const [index, setIndex] = useState<number>(0)

	const onActive = useCallback((i: number) => {
		setIndex(() => i)
	}, [])

	const tab = useMemo(() => {
		return header.map((item, i) => {
			const num = i === index
			return (
				<span
					key={i}
					className={`${styled.login_header_span} ${num && styled.login_header_span_active}`}
					onClick={() => onActive(i)}
				>{item}</span>
			)
		})
	}, [index])

	const form = useMemo(() => {
		if (index === 0) {
			return <FormLogin />
		}
		return <FormRegister />
	}, [index])

	return (
		<div className={styled.login}>
			<div className={styled.login_box}>
				<div className={styled.login_header}>{tab}</div>
				<div className={styled.login_box_form}>{form}</div>
			</div>
		</div>
	)
}

export default Login
